package cn.com.dhcc.turbo.web.controller.monitor;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.DTUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.XstreamUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.app.pub.core.tag.AppTagEl;
import cn.com.dhcc.turbo.entity.api.Posthead;
import cn.com.dhcc.turbo.entity.api.ProcessInfo;
import cn.com.dhcc.turbo.entity.api.RouteLog;
import cn.com.dhcc.turbo.entity.exch.RecvCmData;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo.SL_AUTH_FLAG;
import cn.com.dhcc.turbo.service.exch.cmdata.RecvCmDataService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

@Controller
@RequestMapping("/monitor")
@TurboMenu(belongToMenu=LEAF_MENU.UNCM_STRUC_MONITOR_RECV)
public class RecvCmDataController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

	@Autowired
	private RecvCmDataService cmDataService;
    @Autowired
    private NodeInfoService nodeInfoService;
    @Autowired
    private BaseInfoService baseInfoService;
	@RequestMapping(value = "/recv_cm_data_list")
	public String list(
			Model model, 
			Pager pager, 
			HttpServletRequest request,
			String sendNodecode, 
			String sendAdaptercode, 
			String recvNodecode, 
			String sendStatus,
			String startCreated, 
			String endCreated, 
			String orderName, 
			String notifyStatus,
			String dataType,
			String order) {
		try {
			WhereCondition searchData = new WhereCondition();
			searchData.where().notEq("MSG_TYPE", AppConst.MsgType.GROUP_MSG.value());
			
			UserInfo userInfo = (UserInfo)BaseController.getCurrentUserInfo(request.getSession());
			boolean isSysUser = userInfo.getSlAuthFlag().equalsIgnoreCase(SL_AUTH_FLAG.SYS_USER.getCode());
			NodeInfo localNode=nodeInfoService.getLocalNode();
			List<Map<String,String>> recvNodeList=new ArrayList<Map<String,String>>();
			List<Map<String,String>> recvAdapterList=new ArrayList<Map<String,String>>();
			if (StrUtil.isNotBlank(notifyStatus)) {
				searchData.and().like("NOTIFY_STATUS", notifyStatus);
			}
			if (StrUtil.isNotBlank(sendNodecode)) {
				searchData.and().like("send_nodecode", sendNodecode);
			}
			if (StrUtil.isNotBlank(sendAdaptercode)) {
				searchData.and().like("send_adaptorcode", sendAdaptercode);
			}
			if (StrUtil.isNotBlank(recvNodecode)) {
				searchData.and().like("recv_nodecode", recvNodecode);
			}else if (isSysUser) {
				searchData.and().like("recv_nodecode", baseInfoService.getCurrentNodeInfo().getNodeCode());
				searchData.and().like("recv_adaptorcode", userInfo.getUserName());
				
				//默认选择项
				Map<String,String> recvNodeMap=new HashMap<String, String>();
				recvNodeMap.put("code", localNode.getNodeCode());
				recvNodeMap.put("name", localNode.getNodeName());
				recvNodeList.add(recvNodeMap);
				//默认选择项
				Map<String,String> recvAdapterMap=new HashMap<String, String>();
				recvAdapterMap.put("code", userInfo.getUserName());
				recvAdapterMap.put("name", AppTagEl.adaptorName(userInfo.getUserName()));
				recvAdapterList.add(recvAdapterMap);
			}
			
			if (StrUtil.isNotBlank(dataType)) {
				searchData.and().eq("DATA_TYPE", dataType);
			}
			//这里对发生中的状态进行了处理，把本地发送和远程发送都看做为发送中
			if (StrUtil.isNotBlank(sendStatus)) {
				searchData.and().eq("send_status", sendStatus);
			}
			//时间范围从那天到那天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
				searchData.and().between("created", new BetweenValue(DTUtil.toDateTime(startCreated) , DTUtil.toDateTime(endCreated)));
			}

			//时间范围，大于等于某天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isBlank(endCreated)) {	
				searchData.and().between("created", new BetweenValue(DTUtil.toDateTime(startCreated), null, true, false));
			}

			//时间范围，小于等于某天
			if (StrUtil.isBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {	
				searchData.and().between("created", new BetweenValue(null, DTUtil.toDateTime(endCreated), false, true));
			}
			if (StrUtil.isNotBlank(orderName)) {
				searchData.orderBy(orderName + " " + order);
			} else {
				searchData.orderBy("created  desc");
			}
			PagerData<RecvCmData> datas = cmDataService.getPagerList(pager, searchData);
			model.addAttribute(DATA_KEY, datas.getDatas());
			model.addAttribute("localNode",localNode );
			model.addAttribute("send_node_list", cmDataService.getSendNodeList());
			if (isSysUser && cmDataService.getRecvNodeList().size()<=0) {
				model.addAttribute("recv_node_list", recvNodeList);
			}else{
				model.addAttribute("recv_node_list", cmDataService.getRecvNodeList());
			}
			
			if (isSysUser && cmDataService.getSendAdapterList().size()<=0) {
				model.addAttribute("send_adapter_list", recvAdapterList);
			}else{
				model.addAttribute("send_adapter_list", cmDataService.getSendAdapterList());
			}
			
			model.addAttribute("send_adapter_list", cmDataService.getSendAdapterList());
			
			model.addAttribute("notify_status_list", AppConst.NotifyStatus.values());
			model.addAttribute("send_status_list", AppConst.SendStatus.values());
			setTotoal(model, datas.getTotal());
			return "monitor/recv_cm_data_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}

	/**
	 * 查看页面
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/recv_cm_data_get")
	public String get(Model model, String id) {
		try {
			RecvCmData vo = cmDataService.get(id);
			String payload = vo.getPayload();
			String path = AppConst.CMDATA_STORED_DIR + File.separator + payload;
			File file = new File(path);
			if (file.exists()) {
				String payloadContent = FileUtils.readFileToString(file);
				vo.setPayloadContent(payloadContent);
			} else {
				model.addAttribute("payloadError", "数据报文文件[" + path + "]不存在");
			}
			boolean encryptFlag=false;
			boolean compressFlag=false;
//			System.out.println("**************XstreamUtil.toObject(Posthead.class, vo.getPosthead())**********************"+XstreamUtil.toObject(Posthead.class, vo.getPosthead()));
//			System.out.println("**************getProcesses()**********************"+XstreamUtil.toObject(Posthead.class, vo.getPosthead()).getProcesses());
//			System.out.println("***********************getProcess************************"+XstreamUtil.toObject(Posthead.class, vo.getPosthead()).getProcesses().getProcess());
			
			List<ProcessInfo> proes=XstreamUtil.toObject(Posthead.class, vo.getPosthead()).getProcesses().getProcess();
			
			if (proes!=null && !proes.isEmpty()) {
				String encrypt=proes.get(0).getEncrypt();
				String compress=proes.get(0).getCompress();
				if (encrypt.equals("1")) {
					encryptFlag=true;	
				}else{
					encryptFlag=false;
				}
				if (compress.equals("1")) {
					compressFlag=true;	
				}else{
					compressFlag=false;
				}
				
			}
			model.addAttribute("encrypt",encryptFlag);
			model.addAttribute("compress",compressFlag);
			model.addAttribute("netType", NodeInfoParam.NODE_NET_TYPE);
			String routeLogXml = vo.getRoutelog();
			RouteLog routeLog = XstreamUtil.toObject(RouteLog.class,routeLogXml);
			model.addAttribute(DATA_KEY, vo);
			model.addAttribute("routeLog", routeLog);
			return "monitor/recv_cm_data_get";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}

	/**
	 * 根据ID删除记录
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/recv_cm_data_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(Model model, String id) {
		try {
			cmDataService.delete(id);
			return jsonSuccessResult("删除成功");
		} catch (Exception e) {
			logger.error("删除失败", e);
			return jsonFailResult("删除失败");
		}
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/recv_cm_data_deletes", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteByIds(@RequestParam("ids") String ids) {
		String msg = "";
		try {
			msg = "删除成功";
			cmDataService.deleteBatchById(ids.split(","));
			return jsonSuccessResult(msg);
		} catch (Exception e) {
			msg = "批量删除失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 * 下载消息体
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/recv_cm_data_download")
	public void download(HttpServletResponse response,String id) {
		try {
			RecvCmData vo = cmDataService.get(id);
			String payload = vo.getPayload();
			String path = AppConst.CMDATA_STORED_DIR + File.separator + payload;
			File file = new File(path);
			if (file.exists()) {
				String nameToShow=null;
				//如果是sql类型，生成sql文件
				nameToShow=vo.getId()+".txt";
				downLoadFile(response, file, nameToShow);
			} else {
				logger.error("数据报文文件[" + path + "]不存在");
			}
		} catch (Exception e) {
			logger.error("操作失败", e);
		}
	}
}
